package nyist.media.controller;

import nyist.media.exception.BusinessException;
import nyist.media.page.ApiResult;
import nyist.media.service.QiniuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author dcf
 * @date 2019/3/23
 */

@RestController
@RequestMapping(value = "/common/file", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class FileController {

    @Autowired
    private QiniuService qiniuService;

    /**
     * 多图片上传
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/upload_multi")
    public Map<String, Object> uploadMulti(HttpServletRequest request) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getServletContext());
        if (multipartResolver.isMultipart(request)) {
            List<String> urlList = new ArrayList<>();
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            // 取得上传文件
            for (MultipartFile file : multiRequest.getFileMap().values()) {
                if (file != null && !file.isEmpty()) {
                    try {
                        urlList.add(qiniuService.upload(file.getBytes()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (!urlList.isEmpty()) {
                return ApiResult.SUCCESS.getMap().add("url", urlList);
            }
        }
        return ApiResult.UPLOAD_IMG_FAIL.getMap();
    }


    @PostMapping("/upload_img")
    public Map<String, Object> uploadMulti(MultipartFile file) throws IOException {
        if (file != null && file.isEmpty()) {
            return ApiResult.SUCCESS.getMap().add("url", qiniuService.upload(file.getBytes()));
        }
        throw new BusinessException(ApiResult.UPLOAD_IMG_FAIL);
    }

}
